#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqstack.h"

 //创建栈
sqstack stack_create( int len ){

    sqstack s = ( sqstack )malloc( sizeof( sqnode ) );
    if( s == NULL )
    {
	printf( "malloc sqstack failed\n" );
	return NULL;
    }

    s->data = ( data_t * )malloc( sizeof( data_t ) * len );
    if( s->data == NULL )
    {
	printf("malloc data failed\n");
	free( s );
	return NULL;
    }

    memset( s->data, 0, sizeof( data_t) * len );
    s->maxlen = len;
    s->top = -1;

    return s;
    
}

 //进栈
int stack_push( sqstack s, data_t value ){

    if( s == NULL )
    {
	printf( "s is NULL\n " );
	return -1;
    }

    if( s->top == s->maxlen -1)
    {
	printf( "stack is full\n" );
	return -1;
    }

    s->top++;
    s->data[s->top] = value;

}

//判断栈是否为空
int stack_empty( sqstack s ){

    if( s == NULL )
    {
	printf( "s is NULL\n " );
	return -1;
    }
    
    return s->top == -1 ? 1 : 0;

} 

//判断栈是否满了
int stack_full( sqstack s ){

    if( s == NULL )
    {
	printf( "s is NULL\n " );
	return -1;
    }

    return s->top == ( s->maxlen - 1 ) ? 1 : 0;

} 

//出栈
data_t stack_pop( sqstack s ){

    if( s == NULL )
    {
	printf( "s is NULL\n " );
	return -1;
    }

    if( s->top == -1 )
    {
	printf( "stack not value\n");
	return -1;
    }

    data_t val = s->data[s->top];
    s->top--;

    return val;

} 

//栈顶元素
data_t stack_top( sqstack s ){


    if( s == NULL )
    {
	printf( "s is NULL\n " );
	return -1;
    }

    if( s->top == -1 )
    {
	printf( "stack not value\n");
	return -1;
    }

    return s->data[s->top];
} 

//清栈
int stack_clear( sqstack s )
{
    
    if( s == NULL )
    {
	printf( "s is NULL\n " );
	return -1;
    }

    s->top = -1;
    return 1;
} 

//回收栈
int stack_free( sqstack s ){

    if( s == NULL )
    {
	printf( "s is NULL\n " );
	return -1;
    }

    if( s->data != NULL )
	free( s->data );
    free( s );

} 

